﻿using UnityEngine;

public class SetDestinationOnClick : MonoBehaviour
{
    public FlowFieldPathfinding flowField;
    public GameObject destinationMarkerPrefab;
    
    private GameObject currentMarker;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            
            if (Physics.Raycast(ray, out hit))
            {
                var gridPos = flowField.WorldToGridPosition(hit.point);
                
                if (flowField.IsPositionValid(gridPos) && !flowField.IsAnyObstacle(gridPos))
                {
                    flowField.SetDestination(gridPos);
                    
                    // Update destination marker
                    if (currentMarker == null)
                    {
                        currentMarker = Instantiate(destinationMarkerPrefab);
                        currentMarker.gameObject.SetActive(true);
                    }
                    
                    currentMarker.transform.position = flowField.GridToWorldPosition(gridPos);
                }
            }
        }
    }
}